<template>
  <transition name="fade">
    <div class="sub-category" v-if="filterList">
      <div class="container">
        <!-- 面包屑 -->
        <SubBread />
        <!-- 筛选分区 -->
        <SubFilter />
        <!-- 商品分区 -->
        <div class="goods-list">
          <!-- 排序 -->
          <subSort></subSort>
          <!-- 商品列表 -->
          <ul class="list">
            <li v-for="item in goodsList" :key="item.id">
              <goodsItem :goodsList="item" />
            </li>
          </ul>
        </div>
      </div>
      <!-- 👇瀑布流 -->
      <xtx-infinite
        v-model="onLoading"
        @load="handleLoad"
        :finished="finished"
      ></xtx-infinite>
    </div>
    <SubSkeleton v-else></SubSkeleton>
  </transition>
</template>

<script setup name="SubCategory">
import { provide, ref, watch, reactive } from "vue";
import { useRoute } from "vue-router";
import { findSubFilter, findCategoryGoods } from "@/api/category.js";
import SubBread from "./components/sub-bread.vue";
import SubFilter from "./components/sub-filter.vue";
import SubSkeleton from "./components/sub-skeleton.vue";
import subSort from "./components/sub-sort.vue";
import goodsItem from "./components/goods-item.vue";


// 用于商品列表--分页查询接口的请求参数
const reqParams = reactive({
  categoryId: "",
  sortField: undefined,
  sortMethod: undefined,
  inventory: false,
  onlyDiscount: false
});
// 父组件提供的是响应式对象，子组件内部可以直接修改
provide("reqParams", reqParams);
// 根据请求参数获取商品列表数据
const goodsList = ref([]);
watch(reqParams, async () => {
  // 根据请求参数获取商品列表
  reqPages.page = 1;
  reqPages.pageSize = 10;
  const { result } = await findCategoryGoods({ ...reqParams, ...reqPages });
  reqPages.page++;

  goodsList.value = result.items;
});

// 瀑布流请求数据
const reqPages = reactive({
  page: 1,
  pageSize: 10
});
const onLoading = ref(false); // 数据加载状态
const finished = ref(false); // 数据完全加载
const handleLoad = async () => {
  // 根据请求参数获取商品列表
  onLoading.value = true;
  const { result } = await findCategoryGoods({ ...reqParams, ...reqPages });
  goodsList.value.push(...result.items);
  reqPages.page++;
  onLoading.value = false;
  if (result.items.length < reqPages.pageSize) {
    finished.value = true;
  }
};

// 筛选区
// 骨架屏加载
const filterList = ref(null);
const ROUTE = useRoute();
watch(
  () => ROUTE.params.id,
  async (id) => {
    if (ROUTE.path !== `/category/sub/${id}`) return;
    reqParams.categoryId = id;
    filterList.value = null;
    const { result } = await findSubFilter({ id: id });
    filterList.value = result;
  },
  { immediate: true }
);
provide("filterList", filterList);
</script>

<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
